package cn.gl.usr.service.impl;

import cn.gl.basic.exception.BusinessException;
import cn.gl.basic.jwt.JwtUtils;
import cn.gl.basic.jwt.LoginData;
import cn.gl.basic.jwt.RsaUtils;
import cn.gl.basic.util.AjaxResult;
import cn.gl.basic.util.HttpUtil;
import cn.gl.basic.util.Md5Utils;
import cn.gl.basic.util.StrUtils;
import cn.gl.system.domain.Menu;
import cn.gl.usr.constant.WxConstants;
import cn.gl.usr.domain.Logininfo;
import cn.gl.usr.domain.User;
import cn.gl.usr.domain.Wxuser;
import cn.gl.usr.dto.LoginDto;
import cn.gl.usr.mapper.LogininfoMapper;
import cn.gl.usr.mapper.UserMapper;
import cn.gl.usr.mapper.WxuserMapper;
import cn.gl.usr.service.ILogininfoService;
import cn.gl.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.xb.ltgfmt.Code;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //校验空值
        if (StringUtils.isEmpty(loginDto.getAccount())||StringUtils.isEmpty(loginDto.getCheckPass())){
            throw new BusinessException("信息不能为空");
        }
        //2.校验账号
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if(logininfo==null){//根据账号没有查询到信息
            throw new BusinessException("账号错误!!!");
        }
        //3.校验密码
        String inputMd5Pwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
        if(!inputMd5Pwd.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误!!!");
        }
        //4.校验是否禁用
        if(logininfo.getDisable()==0){
            throw new BusinessException("该账号被禁用，请联系管理员!!!");
        }
        return loginSuccessJwtHandler(logininfo);
    }

    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        //组装URL
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", map.get("code"));
        //将URL使用http工具类转换成字符串
        String jsonStr = HttpUtil.httpGet(url);
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        String access_token = jsonObj.getString("access_token");
        String openid = jsonObj.getString("openid");
        //通过openid去查询wxuser表
        Wxuser wxuser = wxuserMapper.laodByOpenid(openid);
        if (wxuser != null){//不是空值  说明绑定了user
            User user = userMapper.laodOne(wxuser.getUserId());
            if (user != null){//不为空值 说明绑定了logininfo
                //免密登录
                Logininfo logininfo = logininfoMapper.laodOne(user.getLogininfoId());
                Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setObj(resultMap);

            }

        }
        //未查询到用户数据携带token和openid返回前端跳转微信绑定
        return AjaxResult.me().setSuccess(false)
                .setObj("?access_token="+access_token+"&openid="+openid);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        //电话
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //校验空值
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            new BusinessException("信息不能为空");
        }
        //校验验证码是否过期
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if (obj==null) {
            new BusinessException("验证码过期，请重新输入");
        }
        //校验验证码与缓存是否一致
        if (!verifyCode.equals(obj.toString().split(":")[0])) {
            new BusinessException("验证码错误，请重新输入");
        }
        //组装第三个请求
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        //将url转换成对象
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson处理jsonStr - 将jsonObj中的数据转换WxUser对象
        Wxuser wxuser = jsonStr2WxUser(jsonStr); //user_id=null

        //6.创建User对象和Logininfo对象【phone】 - 难度
        User user = userMapper.loadByPhone(phone);
        if(user==null){
            //手机号码没有绑定过
            user = phone2User(phone);
            Logininfo newLogininfo = user2Logininfo(user);

            logininfoMapper.insert(newLogininfo);
            user.setLogininfoId(newLogininfo.getId());
            userMapper.insert(user);
        }
        wxuser.setUserId(user.getId());//微信用户绑定User
        wxuserMapper.insert(wxuser);
        //7.添加数据库：Logininfo对象 - User对象 - WxUser对象
        //8.做免密登录
        Logininfo logininfo = logininfoMapper.laodOne(user.getLogininfoId());
        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setObj(resultMap);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(1);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(12);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Wxuser jsonStr2WxUser(String jsonStr) {
        JSONObject obj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(obj.getString("openid"));
        wxuser.setNickname(obj.getString("nickname"));
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        wxuser.setUnionid(obj.getString("unionid"));
        return wxuser;
    }


    public Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        Map<String,Object> map = new HashMap<>(); //传递给前端的
        LoginData loginData = new LoginData();  //使用jwt加密的
        //1.设置logininfo
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);
        //2.设置permissions,menus - 管理员
        if(logininfo.getType() == 0){
            //设置permissions
            List<String> permissions = logininfoMapper.findPermissionsByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
            //设置menus
            List<Menu> menus = logininfoMapper.findMenusByLogininfoId(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }
        //3.设置jwtToken - 加密 - loginData
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
        //疑问1:jwtToken中已经有登录信息和菜单和权限信息,为什么还要将登录信息和菜单和权限信息放到map? - 前端没有做解密
        //问题2:在登录拦截中没有刷新过期时间
    }
}

